import 'dart:async';

import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:web_socket_channel/io.dart';

///WebSocket服务类
class WebSocketRepository {
  static WebSocketRepository _instance;

  WebSocketRepository._();

  static WebSocketRepository getInstance() {
    if (_instance == null) {
      _instance = new WebSocketRepository._();
    }
    return _instance;
  }

  Map<String, IOWebSocketChannel> _channelMap = Map();

  // ///建立连接
  // IOWebSocketChannel connect(String api) {
  //   if (api == null || api.isEmpty) {
  //     return null;
  //   }
  //   if (_channelMap != null && _channelMap.containsKey(api)) {
  //     return _channelMap[api];
  //   }
  //   IOWebSocketChannel channel;
  //   try {
  //     runZonedGuarded(() {
  //       channel = new IOWebSocketChannel.connect(api);
  //     }, (e, r) {
  //       print("处理:$e");
  //     });
  //     _channelMap[api] = channel;
  //     return channel;
  //   } catch (e, r) {
  //     print(r);
  //     disconnect(channel);
  //     _channelMap?.remove(api);
  //     return null;
  //   }
  // }

  ///建立连接
  IOWebSocketChannel connectAndListener(
    String api, {
    ValueChanged<dynamic> onData,
    ValueChanged<IOWebSocketChannel> onChannel,
  }) {
    if (api == null || api.isEmpty) {
      return null;
    }
    IOWebSocketChannel channel = new IOWebSocketChannel.connect(api);
    channel.stream.listen(
        (event) {
          _onData(event, onData);
        },
        onError: _onError,
        onDone: () {
          disconnect(channel);
          channel = null;
          _onDone(api, onData, onChannel);
        });
    return channel;
  }

  _onDone(
      String api, ValueChanged<dynamic> onData, ValueChanged<IOWebSocketChannel> onChannel) {
    print("onDone");
    IOWebSocketChannel channel = connectAndListener(api,onData: onData,onChannel: onChannel);
    onChannel?.call(channel);
  }

  _onError(err) {
    print("打印错误:${err}");
  }

  _onData(
    event,
    ValueChanged<dynamic> onData,
  ) {
    onData?.call(event);
  }

  ///断开连接
  void disconnect(IOWebSocketChannel channel) {
    if (channel == null) {
      return;
    }
    channel.sink?.close();
  }

  dispose() {}
}
